import { memo, useEffect, useState } from "react";
import TimetableStyle from "./style";
import DataDisplay_content from "../../baseUI/dataDisplay_content/idnex";
import { Divider, ErrorBlock, Tabs } from "antd-mobile";
import { useGetTimetableRecords } from "../../service/timetableRecord";
import { TimetableRecordType } from "../../types/timetableRecord";
import { useAsyncEffect } from "ahooks";
import { useFetch_getCrouseInfo_simple } from "../../service/course";
import { useGetTimetableInfo_simple } from "../../service/timetable";
import dayjs from "dayjs";
import isBetween from "dayjs/plugin/isBetween";
import CourseItem from "./cpms/courseItem";

dayjs.extend(isBetween);

export enum courseLabel {
  ENE = "end",
  GOING = "going",
  FUTURE = "future",
}

export interface timetableCoursetype {
  timetableRecordId: string;
  name: string;
  id: string;
  time: {
    id: string;
    classDay: string;
    startTime: string;
    endTime: string;
  };
  isFuterCurDayCourse: boolean;
}

const Timetable = memo(() => {
  const [timetableRecords, setTimetableRecords] =
    useState<TimetableRecordType[]>();
  const [activeTab, setActiveTab] = useState<courseLabel>(courseLabel.GOING);
  const [analyzeDataLoding, setAnalyzeDataLoding] = useState(false);
  const [endCourses, setEndCourse] = useState<timetableCoursetype[]>();
  const [goingCourses, setGoingCourse] = useState<timetableCoursetype[]>();
  const [futureCourses, setFutureCourse] = useState<timetableCoursetype[]>();

  const { getTimetableRecords, loading: timetableRecordLoading } =
    useGetTimetableRecords();
  const { getCourseInfo } = useFetch_getCrouseInfo_simple();
  const { getTimetableInfo } = useGetTimetableInfo_simple();

  useEffect(() => {
    void getTimetableRecords().then((res) => {
      setTimetableRecords(res.data);
    });
  }, []);
  useAsyncEffect(async () => {
    if (timetableRecords && timetableRecords.length > 0) {
      setAnalyzeDataLoding(true);
      const endArr: timetableCoursetype[] = [];
      const goingArr: timetableCoursetype[] = [];
      const futurArr: timetableCoursetype[] = [];
      for (const schedule of timetableRecords) {
        const t = await getTimetableInfo(schedule.timetableId);
        const c = await getCourseInfo(schedule.courseId);
        const isBefore = dayjs().isBefore(t.classDay, "day");
        const isAfter = dayjs().isAfter(t.classDay, "day");
        const arr = {
          timetableRecordId: schedule.id,
          name: c.name,
          id: c.id,
          time: {
            id: t.id,
            classDay: dayjs(t.classDay).format("YYYY-MM-DD"),
            startTime: t.startTime,
            endTime: t.endTime
          },
          isFuterCurDayCourse: false
        };
        // 未来几天的课程
        if (isBefore) {
          futurArr.push(arr);
        }
        // 过去几天的课程
        else if (isAfter) {
          endArr.push(arr);
        }
        // 当天的课程
        else {
          const startTime = dayjs(dayjs().format("YYYY-MM-DD") + t.startTime);
          const endTime = dayjs(dayjs().format("YYYY-MM-DD") + t.endTime);
          // 正在进行的课程
          if (dayjs().isBetween(startTime, endTime)) {
            goingArr.push(arr);
          } // 已结束课程
          else if (dayjs().isAfter(endTime)) {
            endArr.push(arr);
          }
          // 还未开始的课程
          else {
            futurArr.push({
              ...arr,
              isFuterCurDayCourse: true
            });
          }
        }
      }
      setEndCourse(endArr);
      setGoingCourse(goingArr);
      setFutureCourse(futurArr);
      setAnalyzeDataLoding(false);
    }
  }, [timetableRecords]);
  const cancelReserve = () => {
    void getTimetableRecords().then((res) => {
      setTimetableRecords(res.data);
    });
  };
  return (
    <TimetableStyle>
      <DataDisplay_content
        loading={timetableRecordLoading && analyzeDataLoding}
        title="课程表"
        showReturnBtn={false}
      >
        {timetableRecords?.length === 0 ? (
          <ErrorBlock
            status="empty"
            title="暂无课程"
            description="快去预约课程吧！"
          />
        ) : (
          <Tabs
            activeKey={activeTab}
            onChange={(value) => {
              setActiveTab(value as courseLabel);
            }}
          >
            <Tabs.Tab title="已结束" key="end">
              <Divider>只展示近七天课程</Divider>
              <CourseItem data={endCourses ?? []} label={courseLabel.ENE} />
            </Tabs.Tab>
            <Tabs.Tab title="正在进行" key="going">
              <CourseItem data={goingCourses ?? []} label={courseLabel.GOING} />
            </Tabs.Tab>
            <Tabs.Tab title="未开始" key="future">
              <Divider>不可取消当天课程</Divider>
              <CourseItem
                data={futureCourses ?? []}
                label={courseLabel.FUTURE}
                cancelReserveClick={cancelReserve}
              />
            </Tabs.Tab>
          </Tabs>
        )}
      </DataDisplay_content>
    </TimetableStyle>
  );
});

export default Timetable;
